package com.tuyenmonkey.mkloader.type;

import com.tuyenmonkey.mkloader.model.Arc;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.RectFloat;

import java.math.BigDecimal;


public class PhoneWave extends LoaderView {
  private Arc[] arcs;
  private int numberOfArc;

  public PhoneWave() {
    numberOfArc = 3;
  }

  @Override public void initializeObjects() {
    float r = Math.min(width, height) / 2f;
    arcs = new Arc[numberOfArc];

    for (int i = 0; i < numberOfArc; i++) {
      float d = new BigDecimal(r).divide(new BigDecimal(4)).add(new BigDecimal(i).multiply(new BigDecimal(r)).divide(new BigDecimal(4))).floatValue();

      arcs[i] = new Arc();
      arcs[i].setColor(color);
      arcs[i].setAlpha(126);
      arcs[i].setOval(new RectFloat(new BigDecimal(center.getPointX()).subtract(new BigDecimal(d)).floatValue()
              , new BigDecimal(center.getPointY()).subtract(new BigDecimal(d)).add(new BigDecimal(r).divide(new BigDecimal(3))).floatValue()
              , new BigDecimal(center.getPointX()).add(new BigDecimal(d)).floatValue()
              , new BigDecimal(center.getPointY()).add(new BigDecimal(d)).add(new BigDecimal(r).divide(new BigDecimal(3))).floatValue()));

      arcs[i].setStartAngle(225);
      arcs[i].setSweepAngle(90);
      arcs[i].setStyle(Paint.Style.STROKE_STYLE);
      arcs[i].setWidth(r / 10f);
    }
  }

  @Override public void setUpAnimation() {
    for (int i = 0; i < numberOfArc; i++) {
      final int index = i;

      AnimatorValue fadeAnimator = new AnimatorValue();
      fadeAnimator.setLoopedCount(AnimatorValue.INFINITE);
      fadeAnimator.setDuration(1000);
      fadeAnimator.setDelay(i * 120);
      fadeAnimator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
        @Override
        public void onUpdate(AnimatorValue animatorValue, float v) {
          arcs[index].setAlpha(v);
          if (invalidateListener != null) {
            invalidateListener.reDraw();
          }
        }
      });

      fadeAnimator.start();
    }
  }

  @Override public void draw(Canvas canvas) {
    for (int i = 0; i < numberOfArc; i++) {
      arcs[i].draw(canvas);
    }
  }
}
